package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import dao.BaseDao;
import dao.OrderDao;
import entity.Order;

public class OrderDaoImpl extends BaseDao implements OrderDao {

	private Connection conn;
	private PreparedStatement pstmt;
	private ResultSet rs;
	@Override
	public int add(Order order) {
		int result=0;
    	try {
    		
    		conn = super.getConnection();
    		
    		String sql="insert into `order` (orderNO,subject,phone,amount,body,status,payType,trade_no) values(?,?,?,?,?,?,?,?) ";
    		
    		pstmt = conn.prepareStatement(sql);
    		
    		pstmt.setObject(1, order.getOrderNO());
    		pstmt.setObject(2, order.getSubject());
    		pstmt.setObject(3, order.getPhone());
    		pstmt.setObject(4, order.getAmount());
    		pstmt.setObject(5, order.getBody());
    		pstmt.setObject(6, order.getStatus());
    		pstmt.setObject(7, order.getPayType());
    		pstmt.setObject(8, order.getTrade_no());
    		
    		result = pstmt.executeUpdate();
    		
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
        	super.closeAll(conn, pstmt, rs);
        }
    	return result;
	}
	@Override
	public Order findByOrderNO(String orderNO) {
		Order order = null;
		try {
			conn = super.getConnection();
			String sql = "select * from `order` where orderNO=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setObject(1, orderNO);
			rs = pstmt.executeQuery();
			
			if (rs.next()) {
				order = new Order();
		        order.setId(rs.getInt("id"));
		        order.setOrderNO(rs.getString("orderNO"));
		        order.setSubject(rs.getString("subject"));
		        order.setPhone(rs.getString("phone"));
		        order.setAmount(rs.getDouble("amount"));
		        order.setBody(rs.getString("body"));
		        order.setStatus(rs.getInt("status"));
		        order.setPayType(rs.getInt("payType"));
		        order.setTrade_no(rs.getString("trade_no"));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
        	super.closeAll(conn, pstmt, rs);
        }
		return order;
	}
	@Override
	public int updateStatus(Order order) {
		int result=0;
    	try {
    		
    		conn = super.getConnection();
    		
    		String sql="update `order` set `status`=?,payType=?,trade_no=? where id=? ";
    		
    		pstmt = conn.prepareStatement(sql);
    		
    		pstmt.setObject(1, order.getStatus());
    		pstmt.setObject(2, order.getPayType());
    		pstmt.setObject(3, order.getTrade_no());
    		pstmt.setObject(4, order.getId());
    		
    		result = pstmt.executeUpdate();
    		
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
        	super.closeAll(conn, pstmt, rs);
        }
    	return result;
	}

}
